package com.atguigu.lease.web.admin.controller.apartment;


import com.atguigu.lease.common.result.Result;
import com.atguigu.lease.model.entity.*;
import com.atguigu.lease.model.enums.ItemType;
import com.atguigu.lease.model.enums.ReleaseStatus;
import com.atguigu.lease.web.admin.service.*;
import com.atguigu.lease.web.admin.vo.attr.AttrValueVo;
import com.atguigu.lease.web.admin.vo.graph.GraphVo;
import com.atguigu.lease.web.admin.vo.room.RoomDetailVo;
import com.atguigu.lease.web.admin.vo.room.RoomItemVo;
import com.atguigu.lease.web.admin.vo.room.RoomQueryVo;
import com.atguigu.lease.web.admin.vo.room.RoomSubmitVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

@Tag(name = "房间信息管理")
@RestController
@RequestMapping("/admin/room")
public class RoomController {

    @Autowired
    private RoomInfoService roomInfoService ;

    @Autowired
    private RoomAttrValueService roomAttrValueService;

    @Autowired
    private RoomFacilityService roomFacilityService ;

    @Autowired
    private RoomLabelService roomLabelService ;

    @Autowired
    private RoomPaymentTypeService roomPaymentTypeService;

    @Autowired
    private RoomLeaseTermService roomLeaseTermService ;

    @Autowired
    private GraphInfoService graphInfoService ;

    @Autowired
    private ApartmentInfoService apartmentInfoService;

    @Operation(summary = "保存或更新房间信息")
    @PostMapping("saveOrUpdate")
    public Result saveOrUpdate(@RequestBody RoomSubmitVo roomSubmitVo) {

        Long id = roomSubmitVo.getId();
        if(id!=null){
            //删除旧关系
            roomFacilityService.remove(new LambdaQueryWrapper<RoomFacility>().eq(RoomFacility::getRoomId,id));
            roomLabelService.remove(new LambdaQueryWrapper<RoomLabel>().eq(RoomLabel::getRoomId,id));
            roomLeaseTermService.remove(new LambdaQueryWrapper<RoomLeaseTerm>().eq(RoomLeaseTerm::getRoomId,id));
            roomPaymentTypeService.remove(new LambdaQueryWrapper<RoomPaymentType>().eq(RoomPaymentType::getRoomId,id));
            roomAttrValueService.remove(new LambdaQueryWrapper<RoomAttrValue>().eq(RoomAttrValue::getRoomId,id));
            graphInfoService.remove(new LambdaQueryWrapper<GraphInfo>().eq(GraphInfo::getItemId,id).eq(GraphInfo::getItemType,ItemType.ROOM));
        }

        //1.保存房间本身的信息
        roomInfoService.saveOrUpdate(roomSubmitVo);
        Long roomId = roomSubmitVo.getId();
        //2.保存房间属性关系
        // 房间信息： RoomInfo
        // 属性名称:  AttrKey
        // 属性值  :  AttrValue
        // 房间属性值: RoomAttrValue   <--   RoomAttrValueService
        // 一个房间拥有多个属性值，--> List<Long>   这里的long保存的是AttrValueId
        // AttrValueId + RoomId  封装成了一个对象： RoomAttrValue
        /*
        Collection<RoomAttrValue> roomAttrValueList = roomSubmitVo.getAttrValueIds()
                .stream()
                .map(attrValueId -> RoomAttrValue.builder().roomId(roomId).attrValueId(attrValueId).build())
                .collect(Collectors.toList());
        roomAttrValueService.saveBatch(roomAttrValueList);
        */
        roomAttrValueService.saveBatch(roomSubmitVo.getAttrValueIds()
                .stream()
                .map(attrValueId -> RoomAttrValue.builder().roomId(roomId).attrValueId(attrValueId).build())
                .collect(Collectors.toList()));

        //3. 保存租期关系信息
        roomLeaseTermService.saveBatch(roomSubmitVo.getLeaseTermIds()
                .stream()
                .map(leaseTermId -> RoomLeaseTerm.builder().roomId(roomId).leaseTermId(leaseTermId).build())
                .collect(Collectors.toList())
        );

        //4. 保存配套关系信息
        roomFacilityService.saveBatch(roomSubmitVo.getFacilityInfoIds()
                .stream()
                .map(facilityId -> RoomFacility.builder().roomId(roomId).facilityId(facilityId).build())
                .collect(Collectors.toList()));

        //5. 保存标签关系信息
        roomLabelService.saveBatch(roomSubmitVo.getLabelInfoIds()
                .stream()
                .map(labelId -> RoomLabel.builder().roomId(roomId).labelId(labelId).build())
                .collect(Collectors.toList()));

        //6. 保存支付方式关系信息
        roomPaymentTypeService.saveBatch(roomSubmitVo.getPaymentTypeIds()
                .stream()
                .map(paymentTypeId -> RoomPaymentType.builder().roomId(roomId).paymentTypeId(paymentTypeId).build())
                .collect(Collectors.toList()));

        //7. 保存房间的图片信息
        // 注意： GraphInfo上没有使用@Builder修饰。一般我们的开发经验是：在和表对应的实体类上不允许使用@Builder。(极有可能和mybatis-plus的反射机制冲突)
        graphInfoService.saveBatch(roomSubmitVo.getGraphVoList().stream()
                .map(graphVo->{
                    GraphInfo graphInfo = new GraphInfo() ;
                    BeanUtils.copyProperties(graphVo, graphInfo);
                    graphInfo.setItemType(ItemType.ROOM);
                    graphInfo.setItemId(roomId);
                    return graphInfo;
                }).collect(Collectors.toList()));

        return Result.ok();
    }

    @Operation(summary = "根据条件分页查询房间列表")
    @GetMapping("pageItem")
    public Result<IPage<RoomItemVo>> pageItem(@RequestParam long current, @RequestParam long size, RoomQueryVo queryVo) {
        IPage<RoomItemVo> roomItemVoIPage = roomInfoService.pageItem(Page.of(current, size),queryVo);
        return Result.ok(roomItemVoIPage);
    }

    @Operation(summary = "根据id获取房间详细信息")
    @GetMapping("getDetailById")
    public Result<RoomDetailVo> getDetailById(@RequestParam Long id) {

        //1. 查询房间的基本信息
        RoomInfo roomInfo = roomInfoService.getById(id);

        //复制属性
        RoomDetailVo roomDetailVo = new RoomDetailVo();
        BeanUtils.copyProperties(roomInfo,roomDetailVo);

        //2. 查询房间的各种关联信息

        //2-1. 图片
        List<GraphInfo> graphInfoList = graphInfoService.list(new LambdaQueryWrapper<GraphInfo>()
                .eq(GraphInfo::getItemType, ItemType.ROOM)
                .eq(GraphInfo::getItemId, id));
        roomDetailVo.setGraphVoList(graphInfoList.stream()
                                                .map(graphInfo -> GraphVo.builder()
                                                        .name(graphInfo.getName())
                                                        .url(graphInfo.getUrl()).build())
                                                .collect(Collectors.toList()));
        //2-2. 公寓
        ApartmentInfo apartmentInfo = apartmentInfoService.getById(roomInfo.getApartmentId());
        roomDetailVo.setApartmentInfo(apartmentInfo);

        //2-3. 属性值列表
        List<AttrValueVo> attrValueVoList = roomAttrValueService.getAttrValueVoListByRoomId(id);
        roomDetailVo.setAttrValueVoList(attrValueVoList);

        //2-4. 配套信息列表
        List<FacilityInfo> facilityInfoList = roomFacilityService.getFacilityInfoListByRoomId(id);
        roomDetailVo.setFacilityInfoList(facilityInfoList);

        //2-5. 标签信息列表
        List<LabelInfo> labelInfoList = roomLabelService.getLabelListByRoomId(id);
        roomDetailVo.setLabelInfoList(labelInfoList);

        //2-6. 支付方式列表
         List<PaymentType> paymentTypeList = roomPaymentTypeService.getPaymentTypeListByRoomId(id);
         roomDetailVo.setPaymentTypeList(paymentTypeList);

        //2-7. 租期列表
        List<LeaseTerm> leaseTermList = roomLeaseTermService.getLeaseTermListByRoomId(id);
        roomDetailVo.setLeaseTermList(leaseTermList);

        return Result.ok(roomDetailVo);
    }

    @Operation(summary = "根据id删除房间信息")
    @DeleteMapping("removeById")
    public Result removeById(@RequestParam Long id) {

        //1. 删除各种关系
        roomLeaseTermService.remove(new LambdaQueryWrapper<RoomLeaseTerm>().eq(RoomLeaseTerm::getRoomId,id));
        roomAttrValueService.remove(new LambdaQueryWrapper<RoomAttrValue>().eq(RoomAttrValue::getRoomId,id));
        roomFacilityService.remove(new LambdaQueryWrapper<RoomFacility>().eq(RoomFacility::getRoomId,id));
        roomLabelService.remove(new LambdaQueryWrapper<RoomLabel>().eq(RoomLabel::getRoomId,id));
        roomPaymentTypeService.remove(new LambdaQueryWrapper<RoomPaymentType>().eq(RoomPaymentType::getRoomId,id));
        graphInfoService.remove(new LambdaQueryWrapper<GraphInfo>().eq(GraphInfo::getItemId,id).eq(GraphInfo::getItemType,ItemType.ROOM));

        //2. 删除房间信息本身
        roomInfoService.removeById(id);

        return Result.ok();
    }

    @Operation(summary = "根据id修改房间发布状态")
    @PostMapping("updateReleaseStatusById")
    public Result updateReleaseStatusById(Long id, ReleaseStatus status) {
        roomInfoService.update(new LambdaUpdateWrapper<RoomInfo>().set(RoomInfo::getIsRelease,status).eq(RoomInfo::getId,id));
        return Result.ok();
    }

    @GetMapping("listBasicByApartmentId")
    @Operation(summary = "根据公寓id查询房间列表")
    public Result<List<RoomInfo>> listBasicByApartmentId(Long id) {
        return Result.ok(roomInfoService.list(new LambdaQueryWrapper<RoomInfo>().eq(RoomInfo::getApartmentId,id)));
    }

}


















